import React, {FC, useCallback, useMemo} from "react";
import "./css/GlobalDrawer.less";
import {Drawer} from "antd";
import {coreConnect} from "../utils/StoreUtil.tsx";

interface GlobalDrawerProps {
    list: object[]
}


const GlobalDrawer: FC<GlobalDrawerProps> = (props) => {

    const removeDrawer: Function = useCallback((key: string) => {
        props.dispatch({
            type: "drawerReducer/removeDrawer",
            payload: {
                key: key
            }
        })
    }, []);

    const updateDrawer: Function = useCallback((key: string) => {
        props.dispatch({
            type: "drawerReducer/openDrawer",
            payload: {
                key: key
            }
        })
    }, []);

    const renderGlobalDrawer = useMemo(() => {
        return (
            <div className="sf_core_drawer">
                {props.list?.map((item: any = {}) => {
                    let Com: any = item.component,
                        {modalProps = {}}: { modalProps: any } = item,
                        {isDestroy = true}: { isDestroy: boolean } = modalProps;

                    if (!Com) null;

                    return (
                        <Drawer
                            onClose={() => {
                                item?.onFinish && item.onFinish(item.resultData);
                                isDestroy ? removeDrawer(item.key) : updateDrawer(item.key);
                            }}
                            placement={modalProps.placement || "bottom"}
                            height={modalProps.height || "45vh"}
                            open={item.open}
                            key={item.key}
                            getContainer={item.container || ".sf_core_main_layout_content"}
                            destroyOnClose={isDestroy}
                            className={"sf_core_drawer_main sf_core_drawer" + (item.key ? "_" + item.key : "default") + " " + modalProps.className}
                            {...modalProps}
                        >
                            <Com {...item.comProps} modalKey={item.key}/>
                        </Drawer>
                    )
                })}
            </div>
        )
    }, [props.list]);

    return (renderGlobalDrawer);
};

export default coreConnect("drawerReducer")(GlobalDrawer);